package com.tiyende.credit.loop.ui.fragment

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonFragment
import com.tiyende.credit.loop.configs.TiyendeApiPath
import com.tiyende.credit.loop.configs.TiyendeApiUrl
import com.tiyende.credit.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.credit.loop.databinding.TiyendeFragmentOrderRepayListBinding
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.request.IHttpCallback
import com.tiyende.credit.loop.ui.activity.TiyendeOrderPayStatusActivity
import com.tiyende.credit.loop.ui.adapter.TiyendeOrderRepayListAdapter
import com.tiyende.credit.loop.ui.dialog.TiyendeTipsDialog
import com.tiyende.credit.loop.utils.TiyendeDensityUtil
import com.tiyende.credit.loop.utils.decoration.LinearSpacingItemDecoration
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.utils.helper.TiyendeOrderHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import com.tiyende.credit.loop.utils.track.TrackPointManager
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：待还款列表
 */
class TiyendeOrderRepayListFragment: CommonFragment() {
//    lateinit var binding: TiyendeFragmentOrderRepayListBinding
    // 使用可空类型的 backing property
    private var _binding: TiyendeFragmentOrderRepayListBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var repayAdapter: TiyendeOrderRepayListAdapter? = null
    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentOrderRepayListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        initOrderRepayRefrashView()
        initOrderRepayRecyclerView()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_REPAY_START)
    }

    override fun initTiyendeListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Repay Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"Repay Page")
        }
    }

    override fun loadTiyendeData() {
        val repayList = TiyendeOrderHelper.queryTiyendeOrderRepayList()
        if (repayList.size == 0){
            repayAdapter?.clear()
            val emptyItem = JSONObject()
            emptyItem.put("itemType","emptyItemView")
            repayAdapter?.addFirstItem(emptyItem)
            return
        }
        repayAdapter?.clear()
        repayAdapter?.addMoreData(repayList)
        if (repayList.size > 0){
            showTiyendeConfigNoticeDialog()
        }
    }

    /* 初始化刷新 */
    private fun initOrderRepayRefrashView() {
        _binding?.repayRefreshLayout?.setColorSchemeResources(R.color.theme,R.color.purple_500)
        _binding?.repayRefreshLayout?.setOnRefreshListener {
            publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESH))
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderRepayRecyclerView(){
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.rvOrderRepay?.layoutManager = layoutManager
        val decoration = TiyendeDensityUtil.dp2px(16f)
        _binding?.rvOrderRepay?.addItemDecoration(LinearSpacingItemDecoration(decoration,decoration,decoration,decoration))
        repayAdapter = TiyendeOrderRepayListAdapter(_binding?.rvOrderRepay)
        _binding?.rvOrderRepay?.adapter = repayAdapter
        _binding?.rvOrderRepay?.itemAnimator = DefaultItemAnimator()
        repayAdapter?.setOnItemChildClickListener { _, childView, position ->
            repayAdapter?.let {
                val item = it.getItem(position)
                when(childView.id){
                    R.id.btOrderRepay -> {//还款
                        val orderId = item.optString("orderId")
                        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LOAN_REPAY,"orderId:$orderId")
                        // TODO: 还款页还款按钮 需上报所有埋点
                        TrackPointManager.getInstance().manualReport()

                        onTiyendeOrderPayAction(orderId)
                    }
                }
            }
        }
    }

    /**
     * 待还款列表 根据配置显示公告Dialog
     */
    private fun showTiyendeConfigNoticeDialog(){
        if (!TiyendeConfigsHelper.isTiyendeShowConfigNotice()){
            return
        }

        val noticeInfo = TiyendeConfigsHelper.queryTiyendeConfigNoticeInfo() ?: return
        val maxNum = noticeInfo.optInt("num",1)
        val showNum = TiyendeConfigsHelper.showNoticeNum
        //本地记录的显示公告次数 >= 配置次数
        if (showNum >= maxNum){
            return
        }
        TiyendeConfigsHelper.showNoticeNum = showNum + 1

        val noticeDialog = TiyendeTipsDialog(requireContext())
        noticeDialog.setCancelable(true)
        noticeDialog.setCanceledOnTouchOutside(true)
        noticeDialog.show()
        noticeDialog.isTiyendeDoubleButton(false)
        noticeDialog.addTiyendeTipsIconResource(R.mipmap.tiyende_dialog_tips_icon)
        noticeDialog.addTiyendeBtnOkText(getString(R.string.tiyende_button_confirm))
        var noticeTitle = noticeInfo.optString("noticeTitle")
        var noticeText = noticeInfo.optString("noticeText")
        //高棉语
        if (TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_LANGUAGE_TAGS) == "km"){
            if (noticeInfo.optString("noticeTitle_km","").isNotEmpty()){
                noticeTitle = noticeInfo.optString("noticeTitle_km")
            }
            if (noticeInfo.optString("noticeText_km","").isNotEmpty()){
                noticeText = noticeInfo.optString("noticeText_km")
            }
        }
        noticeDialog.addTiyendeTitleText(noticeTitle)
        noticeDialog.addTiyendeTipsText(noticeText)
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    private fun onTiyendeOrderPayAction(orderId: String){
        showTiyendeLoading()
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("orderId",orderId)
            put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_LOAN_REPAYMENT_LOOP_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hiddenTiyendeLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    var linkUrl = obj.optString("url","")
                    if (linkUrl.isEmpty()){
                        linkUrl = obj.optString("repayUrl","")
                    }

                    //没有还款链接 - 需要进入还款状态页查询还款状态
                    if (linkUrl.isEmpty()){
                        val thirdOrderId = obj.optString("thirdOrderId")
                        showTiyendeOrderPayStatusAction(orderId,thirdOrderId)
                    } else {
                        showTiyendeOrderPayLink(linkUrl)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hiddenTiyendeLoading()
            }
        })
    }

    /**
     * 链接还款
     */
    private fun showTiyendeOrderPayLink(linkUrl: String){
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * pin还款
     */
    private fun showTiyendeOrderPayStatusAction(orderId: String, thirdOrderId: String){
        TiyendeOrderPayStatusActivity.start(requireContext(),orderId,thirdOrderId)
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESHED -> {
                loadTiyendeData()
            }
            TiyendeEventData.TYPE.TIYENDE_ORDER_FINISHED -> {
                hiddenTiyendeLoading()
            }
            else -> {

            }
        }
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        _binding?.repayRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_REPAY_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}